package com.atguigu.yygh.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.client.DictFeignClient;
import com.atguigu.yygh.common.exception.YyghException;
import com.atguigu.yygh.enums.DictEnum;
import com.atguigu.yygh.hosp.mapper.HospitalSetMapper;
import com.atguigu.yygh.hosp.repository.HospitalRepository;
import com.atguigu.yygh.hosp.service.HospitalService;
import com.atguigu.yygh.model.hosp.Hospital;
import com.atguigu.yygh.model.hosp.HospitalSet;
import com.atguigu.yygh.vo.hosp.HospitalQueryVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author mgx
 * @version 1.0
 * @description: TODO
 * @date 2022/8/26 0:09
 */
@Service
public class HospitalServiceImpl implements HospitalService {

    @Autowired
    private HospitalRepository hospitalRepository;

    @Autowired
    private HospitalSetMapper hospitalSetMapper;

    @Resource
    private DictFeignClient dictFeignClient;

    @Override
    public void saveHospital(Map<String, Object> resultMap) {
        // 把map转化为字符串
        String jsonString = JSONObject.toJSONString(resultMap);
        // 把字符串转化为我们的pojo对象
        Hospital hospital = JSONObject.parseObject(jsonString, Hospital.class);
        // 为了判断是添加还是修改，需要到mongodb数据库中根据唯一索引hoscode进行查询
        Hospital collection = hospitalRepository.findByHoscode(hospital.getHoscode());
        if(collection == null) { // 添加操作
            // 给定默认值
            hospital.setStatus(0);
            hospital.setCreateTime(new Date());
            hospital.setUpdateTime(new Date());
            hospital.setIsDeleted(0);
            // 保存
            hospitalRepository.save(hospital);
        }else { // 修改
            hospital.setStatus(collection.getStatus());
            hospital.setCreateTime(collection.getCreateTime());
            hospital.setUpdateTime(new Date());
            hospital.setIsDeleted(collection.getIsDeleted());
            hospital.setId(collection.getId());

            // 修改
            hospitalRepository.save(hospital);
        }
    }

    @Override
    public String getSignKeyWithHoscode(String requestHoscode) {
        // 查询yygh_hosp中的数据库表查询出signkey
        QueryWrapper<HospitalSet> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("hoscode", requestHoscode);
        HospitalSet hospitalSet = hospitalSetMapper.selectOne(queryWrapper);
        if(hospitalSet == null) {
            throw new YyghException(20001, "不存在该医院设置信息");
        }
        return hospitalSet.getSignKey();
    }

    @Override
    public Hospital getHospitalInfoByHoscode(String hoscode) {
        return hospitalRepository.findByHoscode(hoscode);
    }

    @Override
    public Page<Hospital> getHospitalPage(Integer pageNum, Integer pageSize, HospitalQueryVo hospitalQueryVo) {
        // 创建一个hospital对象
        Hospital hospital = new Hospital();
        if(!StringUtils.isEmpty(hospitalQueryVo.getProvinceCode())){
            hospital.setProvinceCode(hospitalQueryVo.getProvinceCode());
        }
        if(!StringUtils.isEmpty(hospitalQueryVo.getDistrictCode())){
            hospital.setDistrictCode(hospitalQueryVo.getDistrictCode());
        }
        if(!StringUtils.isEmpty(hospitalQueryVo.getHosname())) {
            // 模糊查询
            hospital.setHosname(hospitalQueryVo.getHosname());
        }
        if(!StringUtils.isEmpty(hospitalQueryVo.getHostype())) {
            // 模糊查询
            hospital.setHostype(hospitalQueryVo.getHostype());
        }

        if(!StringUtils.isEmpty(hospitalQueryVo.getDistrictCode())) {
            // 模糊查询
            hospital.setDistrictCode(hospitalQueryVo.getDistrictCode());
        }
        //创建匹配器，即如何使用查询条件
        ExampleMatcher matcher = ExampleMatcher.matching() //构建对象
                //.withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING) //改变默认字符串匹配方式：模糊查询
                .withMatcher("hosname", ExampleMatcher.GenericPropertyMatchers.contains())  //hosname字段模糊匹配
                .withIgnoreCase(true); //改变默认大小写忽略方式：忽略大小写
        Example<Hospital> example = Example.of(hospital, matcher);
        Pageable page = PageRequest.of(pageNum - 1, pageSize, Sort.by("createTime").ascending());
        Page<Hospital> pageInfo = hospitalRepository.findAll(example, page);
        // 因为此时省号市区都是编码，需要去调用cmn中的根据编码查询文字的方法
        pageInfo.getContent().stream().forEach(hospital1 -> {
            this.packageHospital(hospital1);
        });
        return pageInfo;
    }

    @Override
    public void updateStatus(String id, Integer status) {
        if(status == 1 || status == 0) {
            // 先查询后修改
            Hospital hospital = hospitalRepository.findById(id).get();
            hospital.setStatus(status);
            hospital.setUpdateTime(new Date());
            hospitalRepository.save(hospital);
        }else {
            throw new YyghException(20001, "状态status修改不正确");
        }
    }

    @Override
    public Hospital detail(String id) {
        Hospital hospital = hospitalRepository.findById(id).get();
        //进行文字赋值
        this.packageHospital(hospital);
        return hospital;
    }

    @Override
    public List<Hospital> findByName(String hosname) {
        // 使用自定义方法对医院名进行模糊查询
        List<Hospital> list = hospitalRepository.findByHosnameLike(hosname);
        return list;
    }

    @Override
    public Hospital findByHoscode(String hoscode) {
        Hospital hospital = hospitalRepository.findByHoscode(hoscode);
        this.packageHospital(hospital);
        return hospital;
    }

    private void packageHospital(Hospital hospital1) {
        // 获取医院每个信息的相关
        String provinceCode = hospital1.getProvinceCode();
        String cityCode = hospital1.getCityCode();
        String districtCode = hospital1.getDistrictCode();

        String value = hospital1.getHostype();

        // 远程调用cmn服务方法
        String provinceName = dictFeignClient.getNameByValue(Long.parseLong(provinceCode));
        String cityName = dictFeignClient.getNameByValue(Long.parseLong(cityCode));
        String districtName = dictFeignClient.getNameByValue(Long.parseLong(districtCode));

        // 获取医院等级
        String hostype = dictFeignClient.getNameByDictCodeAndValue(DictEnum.HOSTYPE.getDictCode(), Long.parseLong(value));

        // 封装到hospital的param参数中
        hospital1.getParam().put("hostypeString", hostype);
        hospital1.getParam().put("fullAddress", provinceName + cityName + districtName + hospital1.getAddress());
    }
}
